﻿using System;
using System.ComponentModel;
using System.Linq;
using System.Reflection;

namespace YanZhiwei.DotNet3._5.Utilities.Common
{
    /// <summary>
    /// 枚举帮助类
    /// </summary>
    public static class EnumHelper
    {
        public static string GetDescriptionFromEnumName(this Enum value)
        {
            DescriptionAttribute _attribute = value.GetType()
                .GetField(value.ToString())
                .GetCustomAttributes(typeof(DescriptionAttribute), false)
                .SingleOrDefault() as DescriptionAttribute;
            return _attribute == null ? value.ToString() : _attribute.Description;

        }
        public static T GetEnumNameFromDescription<T>(this string description)
        {
            var _type = typeof(T);
            if (!_type.IsEnum)
                throw new ArgumentException();
            FieldInfo[] _fields = _type.GetFields();
            var _field = _fields
                            .SelectMany(f => f.GetCustomAttributes(
                                typeof(DescriptionAttribute), false), (
                                    f, a) => new { Field = f, Att = a })
                            .Where(a => ((DescriptionAttribute)a.Att)
                                .Description == description).SingleOrDefault();
            return _field == null ? default(T) : (T)_field.Field.GetRawConstantValue();
        }
    }
}
